<?php

namespace app\index\controller;
use think\Loader;
use think\Db;
use think\Log;

Loader::import('WxPay.WxPay', EXTEND_PATH, '.Api.php');
require_once EXTEND_PATH . "WxPay/WxPay.Config.php";

class Pay extends Base
{

    /**
     * 支付回调接口。
     */
    public function wxPayReturn()
        {
        $testxml = file_get_contents("php://input");

        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));

        $result = json_decode($jsonxml, true);//转成数组

       /* $result = [
            'appid' => 'wxd6d04509791bdc22',
            'bank_type' => 'CFT',
            'cash_fee' => '1',
            'fee_type' => 'CNY',
            'is_subscribe' => 'N',
            'mch_id' => '1401221602',
            'nonce_str' => 'ac4fa4af959db007aedcd5c0a044abc5',
            'openid' => 'o-pL90OAMZM2YWfLjOi6gk6GgEDU',
            'out_trade_no' => 'XB15399291623203008',
            'result_code' => 'SUCCESS',
            'return_code' => 'SUCCESS',
            'sign' => '2C2AB056DD774E90A4FBAB97E1CB5BF8',
            'time_end' => '20180815211727',
            'total_fee' => '30000',
            'trade_type' => 'JSAPI',
            'transaction_id' => '4200000117201807203023620908',
        ];*/

        Log::record($result, 'debug');
        Log::record('获取预支付回调信息', 'debug');//这里为记录异常，根据自己业务选择处理
        if ($result) {


            $result['out_trade_no'] ? $orderSn = $result['out_trade_no'] : exit;
            $order = model('order')->where(['orderSn' => $orderSn])->find();

            if (!$order) {
                Log::record('订单不存在！', 'error');
                exit;
            }

            if ($order['paymentStatus']) {
                Log::record('订单已支付！', 'error');
                exit;
            }

            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                // 更新订单表

                $o_data = [
                    'payTime' => createTime(),
                    'paymentStatus' => 1,
                ];
                $o_res = model('order')->editData($o_data, $order['id']);

                // type 1-雇佣阿姨 2-雇主购买月卡 3-阿姨购买月卡 4-好雇主认证 5-好阿姨认证 6-雇主充值 7-阿姨充值 8-雇主购买年卡 9-阿姨购买年卡
                if ($order['type'] == 1 || $order['type'] == 2 || $order['type'] == 4 || $order['type'] == 6 || $order['type'] == 8) {
                    $cid = $order['employeeId'];
                    $order['type'] == 1 ? $orderSrc = 1 : true; //1-交易订单
                    $order['type'] == 2 ? $orderSrc = 1 : true; //1-交易订单
                    $order['type'] == 4 ? $orderSrc = 1 : true; //1-交易订单
                    $order['type'] == 8 ? $orderSrc = 1 : true; //1-交易订单
                } else {
                    $cid = $order['workId'];
                }

                $user = model('user')->where(['id' => $cid])->find();


                if($order['type'] == 2 || $order['type'] == 3 || $order['type'] == 4 || $order['type'] == 5 || $order['type']==8 || $order['type'] == 9  ){

                    //下单赠送优惠券
                    $coupon_count = model('coupon')->where(['couponType' => 1003])->count();
                    if($coupon_count){
                        $coupon = model('coupon')->getOrderCoupon($cid);
                    }

                }

                if (!$user) {
                    Log::record('用户不存在！', 'error');
                    exit;
                }

                // orderSrc 流水来源	1-交易订单 2-购买月卡 3-提现申请 4-后台操作 5-充值 6-提现失败 7-点亮好xx 8-购买年卡
                $orderSrc = 1;
                if ($order['type'] == 1) {
                    $orderSrc = 1;
                }
                if ($order['type'] == 2 || $order['type'] == 3) {
                    $orderSrc = 2;
                }
                if ($order['type'] == 4 || $order['type'] == 5) {
                    $orderSrc = 7;
                }

                if ($order['type'] == 8 || $order['type'] == 9) {
                    $orderSrc = 8;
                }

                if($order['type'] == 6 || $order['type'] == 7){
                    $orderSrc = 5;
                    //插入资金日志表
                    $l_data = [
                        'moneySn' => createOrderCode('ZJ'),
                        'targetId' => $cid,
                        'orderId' => $order['id'],
                        'orderSrc' => $orderSrc,
                        'moneyType' => 1,
                        'money' => $result['total_fee'] * 0.01, //微信支付单位为分
                        'leftMoney' => $user['money']+$result['total_fee'] * 0.01,
                        'tradeNo' => $result['transaction_id'],
                        'orderSn' => $order['orderSn'],
                        'payType' => 2,
                        'createTime' => createTime(),
                    ];
                    $l_res = model('user_money_log')->editData($l_data);
                    $money=model('user')->where(['id'=>$cid])->update(['money'=>$user['money']+$result['total_fee'] * 0.01]);
                    exit;
                }
                //插入资金日志表
                $l_data = [
                    'moneySn' => createOrderCode('ZJ'),
                    'targetId' => $cid,
                    'orderId' => $order['id'],
                    'orderSrc' => $orderSrc,
                    'moneyType' => 2,
                    'money' => $result['total_fee'] * 0.01, //微信支付单位为分
                    'leftMoney' => $user['money'],
                    'tradeNo' => $result['transaction_id'],
                    'orderSn' => $order['orderSn'],
                    'payType' => 2,
                    'createTime' => createTime(),
                ];
                $l_res = model('user_money_log')->editData($l_data);

                $points = model('user')->editScore($cid,1,$result['total_fee']* 0.01,2,1,'',$order['id']);
                //查询上级用户id
                $user = model('user')->where(['id' =>$cid])->find();
                if($user['leaderId']){
                    //查询上级用户的赏金,魅力分
                    $leader = model('user')->field('id,isPartner,reward,charm')->where(['id' => $user['leaderId']])->find();
                    //获取已启用的系统配置
                    $sy = model('system_config')->where(['status' => 1])->find();
                    if (!$sy) {
                        Log::record('获取系统配置错误！', 'error');
                        exit;
                    }
                    if($order['type']==2 || $order['type']==3 ){
                        $source=1;
                    }
                    if($order['type']==4 || $order['type']==4 ){
                        $source=3;
                    }
                    if($order['type']==8 || $order['type']==9 ){
                        $source=1;
                    }
                    //判断上级用户是不是合伙人
                    if ($leader['isPartner'] == 1) {
                           model('user')->editScore($leader['id'], 1, $result['total_fee']* 0.01 * $sy['partnerInviteReward'], 3, $source, $cid,$order['id']);
                    } else {
                        //一级赏金比率
                        if ($leader['charm'] < $sy['secondInviteValue']) {
                            model('user')->editScore($leader['id'], 1, $result['total_fee']* 0.01 * $sy['firstInviteReward'], 3, $source, $cid,$order['id']);
                        }
                        //二级赏金比率
                        if ($sy['secondInviteValue'] <= $leader['charm'] && $leader['charm'] < $sy['thirdInviteValue']) {
                            model('user')->editScore($leader['id'], 1, $result['total_fee']* 0.01 * $sy['secondInviteReward'], 3, $source, $cid,$order['id']);
                        }
                        //三级赏金比率
                        if ($sy['thirdInviteValue'] <= $leader['charm']) {
                            model('user')->editScore($leader['id'], 1, $result['total_fee']* 0.01 * $sy['thirdInviteReward'], 3, $source, $cid,$order['id']);
                        }
                    }
                }
                if(!empty($order['shareId'])){
                    if($order['shareId']==$cid){

                        Log::record('禁止分享给自己！', 'error');
                        exit;
                    }
                    $reward = model('user')->editScore($order['shareId'],1,$result['total_fee']* 0.01*$sy['shareReward'],3,4,$cid,$order['id']);
                }
                    //使用优惠券
                if($order['isUseCoupon']){
                    $uc_data=[
                        'id'=>$order['userCouponId'],
                        'status'=>2
                    ];
                    model('user_coupon')->editData($uc_data,$uc_data['id']);
                }
                //如果是托管工资
                if($order['type'] == 1 ){
                    $workId=model('order')->where(['orderSn'=>$order['orderSn']])->find();
                    $now = time();
                    $settlementTime = 30 * 86400;
                    $settlementTime = date('Y-m-d H;i:s', $now + $settlementTime);
                    model('user_relation')
                        ->where(['employeeId' =>$cid,'workId' =>$workId['workId']])
                        ->update(['managedWages' =>$result['total_fee'],'settlementTime' => $settlementTime,'trusteeshipStatus' => 1,'orderId' =>$order['id']]);
                }
                //如果是购买月卡
                if($order['type'] == 2 || $order['type'] == 3){

                    //增加vip时间
                    //当前时间戳
                    $now = time();
                 //   $vipTime = 30 * 86400;
                    $vipTime = 3 * 86400;
                    $vipEndTime = $now + $vipTime;

                    $user_data = [
                        'id'=>$cid,
                        'vipEndTime' =>date('Y-m-d H:i:s',$vipEndTime)
                    ];

                   model('user')->editData($user_data,$user_data['id']);

                }

                //如果是购买年卡
                if($order['type'] == 8 || $order['type'] == 9){

                    //增加vip时间
                    //当前时间戳
                    $now = time();

                    $vipTime = 365 * 86400;
                    $vipEndTime = $now + $vipTime;

                    $user_data = [
                        'id'=>$cid,
                        'vipEndTime' =>date('Y-m-d H:i:s',$vipEndTime)
                    ];

                    model('user')->editData($user_data,$user_data['id']);

                }

                if($order['type'] == 2 || $order['type'] == 3 || $order['type'] == 4 || $order['type'] == 5 || $order['type'] == 8 || $order['type'] == 9){  //产生消费订单

                    //查询是否申请合伙人
                    $status = ['<>',1];   //status 1-审核已通过！
                    $apply = model('street_apply')->where(['cid'=>$cid,'status'=>$status])->count();
                    if($apply){
                        model('street_apply')->where(['cid'=>$cid])->update(['status'=>1]);

                        model('user')->where(['id'=>$cid])->update(['isPartner'=>1]);
                    }

                }

                //点亮好XX
                if($order['type']==4 || $order['type']==5){
                    $userType=$user['userType'];
                    if($userType==1){
                        model('user')->where(['id'=>$cid])->update(['isGoodEmployer'=>1]);
                    }
                    elseif($userType==2){
                        model('user')->where(['id'=>$cid])->update(['isGoodWorker'=>1]);
                    }else{
                        $this->err('用户类型错误！');
                    }
                }


                if (!$l_res) {
                    Log::record('订单流水有误！', 'error');
                    exit;
                }


            } else {
                // 支付失败
                Log::record($result, 'error');
                Log::record('支付失败', 'error');

                //判断是否使用优惠券
                if($order['isUseCoupon']){
                    $uc_data=[
                        'id'=>$order['userCouponId'],
                        'status'=>1
                    ];
                    model('user_coupon')->editData($uc_data,$uc_data['id']);
                }

                $order_data=[
                    'id'=>$order['id'],
                    'cancelStatus'=>1
                    ];
                $order_res=model('order')->editData($order_data,$order_data['id']);

            }
        } else {
            Log::record('无回调信息', 'error');
        }
    }


    /**
     * 预支付订单
     */
    public function makeWxPreOrder()
    {
        //传递过来的参数为订单商品总价格
        /**
         *
         * 统一下单，WxPayUnifiedOrder中out_trade_no、body、total_fee、trade_type必填
         * appid、mchid、spbill_create_ip、nonce_str不需要填入
         * @param WxPayUnifiedOrder $inputObj
         * @param int $timeOut
         * @throws WxPayException
         * @return 成功时返回，其他抛异常
         */

        $wxOrderData = new \WxPayUnifiedOrder();
        //唯一订单号
        $wxOrderData->SetOut_trade_no('1223425');
        //代表JSAPI模式，不要修改，公众号支付，H5，小程序都是这个
        $wxOrderData->SetTrade_type('JSAPI');
        //价格，单位为分
        $wxOrderData->SetTotal_fee(1);
        //商品简介
        $wxOrderData->SetBody('零食商贩');
        //使用小程序用户的openid
        $wxOrderData->SetOpenid('o-pL90OR0um31Eoq_weqNA-vQ91M');
        //异步回调验证路径，开发者自定义
        $wxOrderData->SetNotify_url('http://api.guyig.com/index/pay/wxPayReturn');
        //这个是我又封装的一个生成签名的方法
        $order = $this->getPaySignature($wxOrderData);
        $order ? $this->suc($order) : $this->err('发起失败！');
    }

    // 获取与支付信息
    private function getPaySignature($wxOrderData)
    {
        $config = new \WxPayConfig();
        $wxOrder = \WxPayApi::unifiedOrder($config, $wxOrderData);
        // 失败时不会返回result_code
        if ($wxOrder['return_code'] != 'SUCCESS' || $wxOrder['result_code'] != 'SUCCESS') {
            Log::record($wxOrder, 'error');
            Log::record('获取预支付订单失败', 'error');//这里为记录异常，根据自己业务选择处理
            return false;
        }
        $signature = $this->sign($wxOrder);

        return $signature;
    }

    //按照文档要求生成签名，传递给小程序，让小程序拉起支付
    private function sign($wxOrder)
    {
        $config = new \WxPayConfig();
        $jsApiPayData = new \WxPayJsApiPay();
        //传入小程序appid
        $jsApiPayData->SetAppid($config->GetAppId());
        //按照文档，要求是字符串类型
        $jsApiPayData->SetTimeStamp((string)time());
        //生成随机字符串
        $rand = md5(time() . mt_rand(0, 1000));
        $jsApiPayData->SetNonceStr($rand);
        //拼接prepay_id，要注意拼接
        $jsApiPayData->SetPackage('prepay_id=' . $wxOrder['prepay_id']);
        //签名方式md5
        $jsApiPayData->SetSignType('md5');
        //然后调用sdk自带的MakeSign方法生成签名
        $sign = $jsApiPayData->MakeSign($config);
        //然后在使用sdk自带方法获取到上面的我们赋值到成员属性生成的数组
        $rawValues = $jsApiPayData->GetValues();
        //然后我们在数组上加上生成的签名
        $rawValues['paySign'] = $sign;
        //删除appid，因为返回给客户端没有用，所以消除
        unset($rawValues['appId']);
        //返回
        return $rawValues;
    }

}
